import traceback
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET, require_POST
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from course.models import CourseInfo
from copy import deepcopy

# Create your views here.
@require_GET
def courseList(request):
    response = {}
    page = request.GET.get("page")
    if page:  # 分页数据
        courseInfoList = CourseInfo.objects.all().order_by("id")
        pageSize = int(request.GET.get("pageSize"))
        paginator = Paginator(courseInfoList, pageSize)
        try:
            courseInfoPage = paginator.page(page)
        except PageNotAnInteger:
            courseInfoPage = paginator.page(1)
        except EmptyPage:
            courseInfoPage = paginator.page(paginator.num_pages)
        except Exception as e:
            traceback.print_exc()
            rep = HttpResponse()
            rep.status_code = 500
            rep.content = "未知错误"
            return rep

        response["data"] = [ci.toDict() for ci in courseInfoPage]

    else:  # 仅用于测试
        courseInfoList = CourseInfo.objects.all()
        l = [ci.toDict() for ci in courseInfoList[:10]]
        response["data"] = l

    return JsonResponse(response)


@require_GET
def courseDetail(request):  # TODO: 等待课程详情数据再实现
    response = {}
    courseInfo = CourseInfo.objects.get(id=1)
    response["course"] = courseInfo
    return JsonResponse(response)
